package FinalProject;
import Entity.Entity_Product;
import Entity.Entity_Clothing;
import Entity.Entity_Electronics;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ProductFileManager {
    private static final String FILE_PATH = "products.txt";
    private static final int DELETE_RETRY_TIMES = 3; // 删除重试次数
    private static final long DELETE_RETRY_DELAY = 500; // 重试间隔（毫秒）

    // 保存商品：强制删除旧文件+重试机制
    public static void saveProducts(List<Entity_Product> products) {
        File file = new File(FILE_PATH);
        // 重试删除旧文件
        if (!deleteFileWithRetry(file)) {
            System.err.println("❌ 多次删除文件失败，保存终止");
            return;
        }

        // 新建文件并写入
        try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
            for (Entity_Product p : products) {
                if (p instanceof Entity_Clothing) {
                    Entity_Clothing c = (Entity_Clothing) p;
                    pw.println("服装," + c.getId() + "," + c.getName() + "," + 
                               c.getPrice() + "," + c.getDescription() + "," + c.getSize());
                } else if (p instanceof Entity_Electronics) {
                    Entity_Electronics e = (Entity_Electronics) p;
                    pw.println("电子产品," + e.getId() + "," + e.getName() + "," + 
                               e.getPrice() + "," + e.getDescription() + "," + e.getBrand());
                }
            }
            System.out.println("✅ 商品已保存到：" + FILE_PATH);
        } catch (IOException e) {
            System.err.println("❌ 写入文件失败：" + e.getMessage());
        }
    }

    // 带重试的文件删除方法（解决文件占用问题）
    private static boolean deleteFileWithRetry(File file) {
        if (!file.exists()) {
            return true;
        }
        // 设置文件可写权限
        file.setWritable(true);
        for (int i = 0; i < DELETE_RETRY_TIMES; i++) {
            if (file.delete()) {
                System.out.println("✅ 第" + (i + 1) + "次删除文件成功");
                return true;
            }
            System.err.println("⚠️ 第" + (i + 1) + "次删除失败，重试中...");
            try {
                Thread.sleep(DELETE_RETRY_DELAY);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        return false;
    }

    // 读取商品（逻辑不变，增加日志）
    public static List<Entity_Product> loadProducts() {
        List<Entity_Product> products = new ArrayList<>();
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            System.out.println("ℹ️ 未找到商品文件，返回空列表");
            return products;
        }

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split(",");
                if (data.length < 6) {
                    System.err.println("⚠️ 跳过格式错误数据：" + line);
                    continue;
                }

                if (data[0].equals("服装")) {
                    try {
                        Entity_Clothing c = new Entity_Clothing(
                            data[1], data[2], Double.parseDouble(data[3]), data[4], data[5]
                        );
                        products.add(c);
                    } catch (Exception e) {
                        System.err.println("❌ 服装[" + data[2] + "]加载失败：" + e.getMessage());
                    }
                } else if (data[0].equals("电子产品")) {
                    try {
                        Entity_Electronics e = new Entity_Electronics(
                            data[1], data[2], Double.parseDouble(data[3]), data[4], data[5]
                        );
                        products.add(e);
                    } catch (Exception e) {
                        System.err.println("❌ 电子产品[" + data[2] + "]加载失败：" + e.getMessage());
                    }
                }
            }
            System.out.println("✅ 读取成功，共" + products.size() + "件商品");
        } catch (IOException e) {
            System.err.println("❌ 读取文件失败：" + e.getMessage());
        }
        return products;
    }
}